package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {


    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        //创建结果集对象
//        Result result;
//        if (flag){
//            result=new Result(Code.SAVE_OK,flag,"添加成功")
//        }else {
//            result=new Result(Code.SAVE_ERR,flag,"保存失败");
//        }
//        return result;
         Result result=flag ? new Result(Code.SAVE_OK,flag,"添加成功"):new Result(Code.SAVE_ERR,flag,"保存失败");
         return result;
    }

    @PutMapping
    public Result update(@RequestBody Book book) {

        boolean flag = bookService.update(book);
        Result result = flag ? new Result(Code.UPDATE_OK,flag,"添加成功"):new Result(Code.UPDATE_ERR,flag,"添加失败");

        return result;
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        Result result=flag? new Result(Code.DELETE_OK,flag,"删除成功"): new Result(Code.DELETE_ERR,flag,"删除失败");

        return result;
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Book book = bookService.getById(id);
        Result result = book!=null? new Result(Code.GET_OK,book,"查询单个成功")
                :  new Result(Code.GET_ERR,null,"查询单个失败");
        return   result;
    }

    @GetMapping
    public Result getAll() {

        List<Book> books = bookService.getAll();
        Result result= books!= null && books.size()>0 ? new Result(Code.GET_OK,books,"查询全部成功")
                :new Result(Code.GET_ERR,null,"查询全部失败");
        return  result;
    }
}
